import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage.js'

// 路由懒加载方式
const Tabbar = () => import('@/components/app-tabbar.vue')
const HomeTabbar = () => import('@/views/HomeTabbar')
const QuestionTabbar = () => import('@/views/QuestionTabbar')
const VideoTabbar = () => import('@/views/VideoTabbar')
const UserTabbar = () => import('@/views/UserTabbar')
const MyArticle = () => import('@/views/MyArticle')
const MyLogin = () => import('@/views/MyLogin')
const routes = [
  // 路由规则
  { path: '/', components: { default: HomeTabbar, tabbar: Tabbar } },
  { path: '/question', components: { default: QuestionTabbar, tabbar: Tabbar } },
  { path: '/video', components: { default: VideoTabbar, tabbar: Tabbar } },
  { path: '/user', components: { default: UserTabbar, tabbar: Tabbar } },
  { path: '/article', component: MyArticle },
  { path: '/login', component: MyLogin }
]
Vue.use(VueRouter)
const router = new VueRouter({
  routes
})
// 导航守卫
router.beforeEach((to, from, next) => {
  const token = getToken()
  // 没登录并且访问/user下的路由
  if (!token && to.path.startsWith('/user')) {
    return next('/login?returnUrl=' + encodeURIComponent(from.fullPath))
  }
  // 其他情况放行
  next()
})
export default router
